import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/finished_in_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/finish_in.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:quiver/strings.dart';
import 'finished_in_dialog.dart';
import 'finished_in_scan.dart';

class FinishedInList extends StatefulWidget {
  FinishedInList({Key? key}) : super(key: key);

  @override
  _FinishedInListListState createState() => _FinishedInListListState();
}

class _FinishedInListListState extends State<FinishedInList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  FinishedIn finishedIn = FinishedIn();
  List<FinishedIn> selectedList = [];
  //车间
  List<SelectOptionVO> workshopList = [];
  //源库房
  List<SelectOptionVO> locationList = [];

  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      // _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    if (userInfo.major != null) {
      workshopList = await DynamicDataApi.getModelSelect(
          model: "hr.department",
          name: "complete_name",
          key: "parent_id",
          operator: "!=",
          val: null);
    } else {
      locationList = await DynamicDataApi.getModelSelect(
          active: false,
          model: "stock.location",
          name: "complete_name",
          key: 'workshop_id',
          val: int.parse(userInfo.deptId!),
          key2: 'comment',
          val2: "CPK");
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          userInfo.major != null
              ? CrySelect(
                  width: 280,
                  label: '生产车间',
                  dataList: workshopList,
                  value: finishedIn.workshopId,
                  onSaved: (v) {
                    finishedIn.workshopId = v;
                  },
                  onChange: (v) async {
                    if (finishedIn.workshopId != v) {
                      formKey.currentState!.save();
                      finishedIn.workshopId = v;
                      finishedIn.locationId = null;
                      try {
                        locationList = await DynamicDataApi.getModelSelect(
                            active: false,
                            model: "stock.location",
                            name: "complete_name",
                            key: 'workshop_id',
                            val: int.parse(v),
                            key2: 'comment',
                            val2: "CPK");
                      } catch (e) {
                        locationList = [];
                      }
                      setState(() {});
                    }
                  },
                )
              : CryInput(
                  width: 200,
                  label: '生产车间',
                  enable: false,
                  value: userInfo.deptName,
                ),
          CrySelect(
            width: 380,
            label: '库房',
            dataList: locationList,
            value: finishedIn.locationId,
            onSaved: (v) {
              finishedIn.locationId = v;
            },
          ),
          CryInput(
            width: 180,
            label: '生产订单号',
            value: finishedIn.productorderno,
            onSaved: (v) {
              finishedIn.productorderno = v;
            },
          ),
          CryInput(
            width: 160,
            label: '物料名称',
            value: finishedIn.productName,
            onSaved: (v) {
              finishedIn.productName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('生产订单号')),
        DataColumn(label: Text('物料编码')),
        DataColumn(label: Text('物料名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('批次号')),
        DataColumn(label: Text('库存数量')),
        DataColumn(label: Text('计量单位')),
        DataColumn(label: Text('库房位置')),
      ],
      getCells: (m) {
        FinishedIn finishedIn = FinishedIn.fromMap(m);
        return [
          DataCell(Text(finishedIn.productorderno ?? '--')),
          DataCell(Text(finishedIn.productCode ?? '--')),
          DataCell(Text(finishedIn.productName ?? '--')),
          DataCell(Text(finishedIn.productstyle ?? '--')),
          DataCell(Text(finishedIn.batchno ?? '--')),
          DataCell(Text(finishedIn.stockqty ?? '--')),
          DataCell(Text(finishedIn.unitname ?? '--')),
          DataCell(Text(finishedIn.warehouseId ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        // CryButton(
        //     label: "扫码入库",
        //     iconData: Icons.view_headline,
        //     onPressed: () => {_scan()}),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    finishedIn = FinishedIn();
    formKey.currentState!.reset();
    if (userInfo.major != null) {
      locationList = [];
    }
    tableKey.currentState?.pageTo(0);
    tableKey.currentState?.loadData(PageModel());
    setState(() {});
    // _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    if (isBlank(finishedIn.locationId)) {
      tableKey.currentState?.pageTo(0);
      tableKey.currentState?.loadData(PageModel());
      CryUtils.message("请选择库房位置");
      return;
    }
    ResponseBodyApi responseBodyApi = await FinishedInOdooApi.page(
        data: {"page": page, "domainList": finishedIn.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: FinishedInDialog(),
      ),
    ).then((v) {
      if (v != null) {
        finishedIn = v;
        _query();
      }
    });
  }

  _scan() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: FinishedInScanList(),
      ),
    ).then((v) {
      if (v != null) {
        print(v);
      }
    });
    // Utils.fullscreenDialog(FinishedInScan());
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<FinishedIn>((e) => FinishedIn.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.dmsFile) {
          _scan();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          child: ListTile(
            leading: const Icon(Icons.qr_code_scanner_outlined),
            title: Text('扫码'),
          ),
        ),
      ],
    );
  }
}
